<?php
/**
 * 菜单相关
 */

namespace App\Http\Repositories\Admin;

use App\Exceptions\ApiException;
use App\Http\Repositories\BaseRepository;
use App\Http\Models\Admin\MenuModel;

class MenuRepository extends BaseRepository
{
    private $menu;
    public function __construct(MenuModel $menu)
    {
        $this->menu = $menu;
    }

    /**
     * 获取详情
     * @param $data
     * @return array
     * @throws ApiException
     */
    public function getMenuInfo($data)
    {
        $res = $this->menu->find($data['id']);
        if (empty($res))
            throw new ApiException(ApiException::ERROR_DATA_NOT_EXISTS);

        return $res;
    }

    /**
     * 获取列表
     * @param $data
     * @return array
     */
    public function getMenuList($data)
    {
        $where = [];
        isset($data['menu']) && $where['menu'] = ['like', '%'.$data['menu'].'%'];
        isset($data['path']) && $where['path'] = ['like', $data['path'].'%'];
        isset($data['status']) && $where['status'] = $data['status'];
        isset($data['is_show']) && $where['is_show'] = $data['is_show'];
        isset($data['create_time']) && $where['create_time'] = ['between', $data['create_time']];
        isset($data['update_time']) && $where['update_time'] = ['between', $data['update_time']];

        return $this->menu->getListByPage($where, ['*'], config('pageSize'));
    }

    public function getMenuTreeList($data)
    {
        $where['is_show'] = 1;
        $res = $this->menu->getMenuList($where);

        return $this->generateTree($res);
    }
    /**
     * 添加
     * @param $data
     * @return mixed
     */
    public function addMenu($data)
    {
        !isset($data['status']) && $data['status'] = 1;
        !isset($data['is_show']) && $data['is_show'] = 2;
        !isset($data['sort']) && $data['sort'] = 1;
        if(!isset($data['icon']) && empty($data['icon']))
            unset($data['icon']);
        return $this->menu->addItem($data);
    }

    /**
     * 删除
     * @param $data
     * @return array
     */
    public function delMenu($data)
    {
        return $this->menu->deleteItem($data);
    }

    /**
     * 编辑
     * @param $data
     * @return array
     * @throws ApiException
     */
    public function editMenu($data)
    {
        $menu = $this->menu->find($data['id']);
        if (empty($menu)) {
            throw new ApiException(ApiException::ERROR_DATA_NOT_EXISTS);
        }

        $menu->update($data);

        return [];
    }
}
